package coreconcurrency.unsafe;

/**
 * create by yongli on 2021-11-28 09:31
 * 指令重排在多线程情况下，可能会发生错误。
 * 一段代码拆分成两部分，分别由两个线程调度执行
 * 明显的发生了指令重排!!!
 * 可以看出，使用volatile禁止指令重排很重要
 */

public class CommandReOrdering {

    private static boolean initialized = false;

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                CommandReOrdering.reed();
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                CommandReOrdering.load();
            }
        });

        thread1.start();
        thread2.start();
    }

    public static void reed() {
        try {
            // 假设在读取配置文件，比较耗时
            Thread.currentThread().sleep(10000);
        } catch (Exception e) {
        }
        System.out.println("读取完毕");
        initialized = true;
    }

    public static void load() {
        while (initialized) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("加载完毕");

    }


}
